import axios from "axios";
// import _ from "lodash";
// import md5 from "md5";
import querystring from "querystring";
// import NProgress from "nprogress";
// import { getCache, setCache } from "./js-cache";
import { Toast } from "vant";
import { router } from "@/router";
import { getToken } from "@/utils/auth";
import { BASE_API, secretKey, appVersion, version } from "../config";
// window.md5 = md5;
// NProgress.configure({
//   // showSpinner: false
//   trickle: false
// });
let loading = null;
const headers = {
  "content-type": "application/x-www-form-urlencoded"
};
// create an axios instance
const service = axios.create({
  baseURL: BASE_API,
  timeout: 1000 * 15,
  headers
});
// service.caches = {};

function formatObject(object) {
  // const newObject = {
  //   // appVersion,
  //   // version
  // };
  // for (const key in object) {
  //   // if (object.hasOwnProperty(key)) {
  //   const element = object[key];

  //   if (typeof element === "boolean") {
  //     newObject[key] = element;
  //     continue;
  //   }

  //   if (typeof element === "number") {
  //     newObject[key] = element;
  //     continue;
  //   }

  //   if (element) {
  //     newObject[key] = element;
  //   }
  // }

  // const sortAfter = objKeySort({ ...newObject, secretKey });
  return {
    data: object,
    headers: {
      timestamp: new Date() - 0,
      notsignature: "b5654518a61c47e4b7cec263a2deba1c"
    }
  };
}

function objKeySort(obj) {
  //排序的函数
  var newkey = Object.keys(obj).sort(); //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) {
    //遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj; //返回排好序的新对象
}

// request interceptor
service.interceptors.request.use(
  config => {
    // config.headers = { ...headers, timestamp: "", notsignature: "" };
    // console.log("异步请求:", config);
    // NProgress.start();
    // Toast.loading({ mask: true });
    // Do something before request is sent
    const token = getToken();
    if (!config.data) {
      config.data = {};
    }
    if (!config.noToken) {
      config.data.token = token;
    }

    if (config.method === "post" || config.method === "put") {
      if (config.data instanceof FormData) {
        config.headers["Content-Type"] = "multipart/form-data";
        return config;
      }

      const fmt = formatObject(config.data);

      config.headers = Object.assign(config.headers, fmt.headers);
      config.data = querystring.stringify(fmt.data);
    }

    return config;
  },
  error => {
    // NProgress.done();
    // Toast.clear();
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone interceptor
/**
 * 202 授权失败
 * 201 普通用户
 */
service.interceptors.response.use(
  ({ data, config }) => {
    // console.log(config);
    // NProgress.done();
    // Toast.clear();

    if (typeof data.resultCode == "number") {
      data.code = data.resultCode;
    }

    if (data.code !== 0) {
      if ([415, 416].includes(data.code)) {
        // console.log(router)
        // Toast.fail(data.msg);
        return router.push({ name: "partner-login" });
      }

      if (data.code < 200 || data.code >= 300) {
        Toast.fail(data.msg);
      }

      return Promise.reject(data);
    }

    return data;
  },

  (error, b, c) => {
    console.log("err", error, b, c); // for debug
    // NProgress.done();
    // Toast.clear();

    if (("" + error).indexOf("500") >= 0) {
      // return
      Toast.fail("请求超时.");
    } else {
      Toast.fail(error.message);
    }

    return Promise.reject(error);
  }
);

export default service;
